package com.yape.webCrawler;

import com.yape.webCrawler.base.Crawler;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Hazuki
 * @Date 2025/5/23 下午6:45
 * @Version 1.0
 */
@Service
public class CrawlerService {
    private final Map<String, Crawler> crawlers;

    /**
     * spring自动注入爬虫服务
     * @param crawlers
     */
    public CrawlerService(Map<String, Crawler> crawlers) {
        this.crawlers = crawlers;
    }


    /**
     * 获取所有注册的爬虫
     * @return 所有注册的爬虫
     */
    public Map<String, Crawler> getAllCrawlers() {
        return new HashMap<>(crawlers);
    }

    /**
     * 获取指定名称的爬虫
     * @param name 爬虫名称
     * @return 爬虫实例
     */
    public Crawler getCrawler(String name) {
        return crawlers.get(name);
    }

    /**
     * 执行爬虫并返回结果
     * @param name 爬虫名称
     * @return 爬虫执行结果
     * @throws IOException 执行过程中可能抛出的IO异常
     */
    public Object executeCrawler(String name) throws IOException {
        Crawler crawler = crawlers.get(name);
        if (crawler != null) {
            Object result = crawler.execute();
            return result;
        } else {
            throw new IllegalArgumentException("爬虫未找到: " + name);
        }
    }

    /**
     * 执行爬虫并返回指定类型的结果
     * @param name 爬虫名称
     * @param resultClass 结果类型
     * @param <T> 返回值类型
     * @return 爬虫执行结果
     * @throws IOException 执行过程中可能抛出的IO异常
     */
    public <T> T executeCrawler(String name, Class<T> resultClass) throws IOException {
        Object result = executeCrawler(name);
        if (result == null) {
            return null;
        }
        if (resultClass.isInstance(result)) {
            return resultClass.cast(result);
        } else {
            throw new ClassCastException("爬虫结果类型不匹配: 期望 " + resultClass.getName() +
                    ", 实际 " + result.getClass().getName());
        }
    }
}
